package loader;

import server.HttpServlet;
import sun.reflect.Reflection;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class WebappLoader extends ClassLoader {

    private final String path;

    public WebappLoader( String path) {
        this.path = path;
    }



    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        byte[] data = new byte[0];
        Class clazz = null;
        try {

            clazz =  findLoadedClass(name);
            if (clazz != null){
                return clazz;
            }
            try {
                data = readBytes(name);
                if (data.length > 0 ){
                    clazz = defineClass(name,data,0,data.length);
                    if (clazz != null){
                        return clazz;
                    }
                }
            }catch (Exception e){

            }

            if (clazz == null ){
                clazz = Class.forName(name,false,getSystemClassLoader());
            }
            if (clazz != null){
                return clazz;
            }

        }catch (Exception e){

        }


        return clazz;
    }

    private byte[] readBytes(String name) {

        byte[] data = new byte[0];
        try {

            name = name.replace('.', File.separatorChar) + ".class";
            System.out.println(name);
            FileInputStream is = new FileInputStream(path + "/" + name);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len = 0;
            try {
                while ((len = is.read()) != -1) {
                    bos.write(len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            data = bos.toByteArray();
            is.close();
            bos.close();
        }catch (Exception e){

        }
        return data;
    }


    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {

        WebappLoader webappLoader = new WebappLoader("/Users/handadao/Documents/lagou/Minicat/webapp/app1");

        Class<?>  clazz =  webappLoader.loadClass("server.LagouServlet");

        HttpServlet httpServlet = (HttpServlet) clazz.newInstance();

        System.out.println(httpServlet);

    }
}
